package com.ligongmusic.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Text;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ligongmusic.R;
import com.ligongmusic.adapter.UniversalAdapter;
import com.ligongmusic.adapter.ViewHolder;
import com.ligongmusic.domain.Upload;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.LoggerUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.NetWorkUtils.NetWorkCallBack;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.TopManager;
import com.ligongmusic.view.XListView;
import com.ligongmusic.view.XListView.IXListViewListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

public class MyUpload extends Activity implements IXListViewListener, NetWorkCallBack {
    //	private XListView mListView;
    private Handler mHandler = new Handler();
    private boolean hasData = true;
    private int page = 0, size = 200;
    private UniversalAdapter<Upload> adapter = null;
    //	private List<Upload> uploads ;
    private Map<Integer, List<Upload>> listMap;

    public static DisplayImageOptions options2 = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.music_icon) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.music_icon)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.music_icon)  //设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)//设置下载的图片是否缓存在内存中
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
            .build();//构建完成;
    private ExpandableListView mExpandable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_upload);
        TopManager.getTopManager(this).showTop(true, "我的上传", new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//		mListView = (XListView) findViewById(R.id.upload_list);
//		mListView.setXListViewListener(this);
        mExpandable = (ExpandableListView) findViewById(R.id.expandable);
        getUpload();
    }

    private void getUpload() {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("token", GlobalParams.token));
        pairs.add(new BasicNameValuePair("loginname", GlobalParams.userName));
        pairs.add(new BasicNameValuePair("page", page + ""));
        pairs.add(new BasicNameValuePair("size", size + ""));
        NetWorkUtils.getRequest(pairs, GlobalParams.MY_UPLOAD, this);
    }

    @Override
    public void onRefresh() {
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				hasData = true;
//				page = 0;
//				getUpload();
//			}
//		}, 1000);
    }

    private void onLoad() {
//		mListView.stopRefresh();
//		mListView.stopLoadMore();
//		mListView.setRefreshTime(StringUtils.getTime(System.currentTimeMillis()));
    }

    @Override
    public void onLoadMore() {
//		mHandler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				if(hasData){
//					page ++;
//					getUpload();
//				}else{
//					onLoad();
//				}
//			}
//		}, 1000);
    }

    /**
     * 设置数据适配器
     */
    private void setAdapter() {

        mExpandable.setAdapter(new MyAdapter());
        for (int i = 0; i < listMap.size(); i++)
            mExpandable.expandGroup(i);

//		if(adapter == null){
//			adapter = new UniversalAdapter<Upload>(MyUpload.this, uploads, R.layout.upload_item) {
//				@Override
//				public void convert(ViewHolder holder, final Upload t, int position) {
//					ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getCover(), (ImageView)holder.getView(R.id.music_icon), options2);
//					holder.setText(R.id.music_name, t.getSongname());
//					holder.setText(R.id.upload_date, StringUtils.ms2Date(t.getUploaddate()));
//					holder.setText(R.id.singer_name, t.getMusician().getMusicianname() + "");
//					ImageView iv_add = holder.getView(R.id.iv_add);
//					ImageView iv_detail = holder.getView(R.id.iv_detail);
//					final LinearLayout ll_detail = holder.getView(R.id.ll_detail);
//					iv_detail.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							ll_detail.setVisibility(ll_detail.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
//						}
//					});
//					iv_add.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							// TODO 补充上传详情
//							Intent intent = new Intent(MyUpload.this, SupplementMusic.class);
//							intent.putExtra("music", t);
//							startActivityForResult(intent, 0x1);
//						}
//					});
//					TextView comment = holder.getView(R.id.tv_comment);
//					TextView prise = holder.getView(R.id.tv_prise);
//					prise.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							// TODO 赞列表
//							Intent intent = new Intent(MyUpload.this, PriseList.class);
//							intent.putExtra("comments", t);
//							startActivity(intent);
//						}
//					});
//					comment.setOnClickListener(new OnClickListener() {
//						@Override
//						public void onClick(View v) {
//							Intent intent = new Intent(MyUpload.this, CommentList.class);
////							Bundle bundle = new Bundle();
////							bundle.putSerializable("comments", t);
////							intent.putExtras(bundle);
//							intent.putExtra("comments", t);
//							startActivity(intent);
//						}
//					});
//
////					holder.setText(R.id.prise_num, "赞（" + t.getLikecount() + "）");
////					holder.setText(R.id.comment_num, "评论（" + t.getCommentcount() + "）");
//				}
//			};
//			mListView.setAdapter(adapter);
//		}else
//			adapter.refresh(uploads);
    }

    @Override
    public void success(String result) {
        LoggerUtils.getLog(MyUpload.class).error(result);
        onLoad();
        if (listMap == null)
            listMap = new HashMap<Integer, List<Upload>>();
//		if(uploads == null)
//			uploads = new ArrayList<Upload>();
        if (page == 0)
            listMap.clear();
        List<Upload> temp = JsonUtils.jsonToBeanList(result, Upload.class);
        if (temp == null) {
            return;
        }
//		mListView.setPullLoadEnable(temp.size() == 20);
        hasData = temp.size() == size;
//		Map<Integer, List<Upload>> tempMap = new HashMap<Integer, List<Upload>>();
        List<Upload> shenHe = new ArrayList<Upload>();
        List<Upload> weiShenHe = new ArrayList<Upload>();
        List<Upload> shenHeShibai = new ArrayList<Upload>();
        for (Upload u : temp) {
            if (u.getIsverified() == 0) {
                weiShenHe.add(u);
            } else if (u.getIsverified() == 1) {
                shenHe.add(u);
            } else if (u.getIsverified() == 2) {
                shenHeShibai.add(u);
            }
        }
        if (listMap.containsKey(0)) {
            List<Upload> uploads = listMap.get(0);
            for (int i = 0; i < weiShenHe.size(); i++)
                uploads.add(weiShenHe.get(i));
            listMap.put(0, uploads);
        }else
            listMap.put(0, weiShenHe);
        if (listMap.containsKey(1)) {
            List<Upload> uploads = listMap.get(1);
            for (int i = 0; i < shenHe.size(); i++)
                uploads.add(shenHe.get(i));
            listMap.put(0, uploads);
        }else
            listMap.put(1, shenHe);
        if (listMap.containsKey(2)) {
            List<Upload> uploads = listMap.get(2);
            for (int i = 0; i < shenHeShibai.size(); i++)
                uploads.add(shenHeShibai.get(i));
            listMap.put(0, uploads);
        }else
            listMap.put(2, shenHeShibai);
//		listMap.put(0, listMap.get(0).add)
//			uploads.add(u);

        setAdapter();
    }

    @Override
    public void error() {
        // TODO Auto-generated method stub
    }

    @Override
    public void error(String message) {
        LoggerUtils.getLog(MyUpload.class).error(message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x2 && requestCode == 0x1) {
            hasData = true;
            page = 0;
            getUpload();
        }
    }

    class MyAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            LoggerUtils.getLog(MyUpload.class).error(listMap.size() + "");
            return listMap.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return listMap.get(groupPosition) == null ? 0 : listMap.get(groupPosition).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return listMap.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return listMap.get(groupPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(MyUpload.this, R.layout.group_item, null);
            }
            TextView title = (TextView) convertView.findViewById(R.id.title);
            title.setText(groupPosition == 0 ? "未审核" : groupPosition == 1 ? "已审核" : "审核未通过");
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(MyUpload.this, R.layout.upload_item, null);
            }
            final Upload t = listMap.get(groupPosition).get(childPosition);
            ImageLoader.getInstance().displayImage(GlobalParams.IMAGE_URL + t.getCover(), (ImageView) convertView.findViewById(R.id.music_icon), options2);
            TextView music_name = (TextView) convertView.findViewById(R.id.music_name);
            music_name.setText(t.getSongname());
            TextView upload_date = (TextView) convertView.findViewById(R.id.upload_date);
            TextView singer_name = (TextView) convertView.findViewById(R.id.singer_name);
            upload_date.setText(StringUtils.ms2Date(t.getUploaddate()));
            singer_name.setText(t.getMusician().getMusicianname() + "");
            ImageView iv_add = (ImageView) convertView.findViewById(R.id.iv_add);
            ImageView iv_detail = (ImageView) convertView.findViewById(R.id.iv_detail);
            final LinearLayout ll_detail = (LinearLayout) convertView.findViewById(R.id.ll_detail);
            iv_detail.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ll_detail.setVisibility(ll_detail.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                }
            });
            iv_add.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO 补充上传详情
                    Intent intent = new Intent(MyUpload.this, SupplementMusic.class);
                    intent.putExtra("music", t);
                    startActivityForResult(intent, 0x1);
                }
            });
            TextView comment = (TextView) convertView.findViewById(R.id.tv_comment);
            TextView prise = (TextView) convertView.findViewById(R.id.tv_prise);
            prise.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO 赞列表
                    Intent intent = new Intent(MyUpload.this, PriseList.class);
                    intent.putExtra("comments", t);
                    startActivity(intent);
                }
            });
            comment.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MyUpload.this, CommentList.class);
                    intent.putExtra("comments", t);
                    startActivity(intent);
                }
            });
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}
